import pandas as pd
import json
from pyecharts import options as opts
from pyecharts.charts import Line, Grid


def get_model_trend_analysis(top_n=5):
    """
    获取热门车型年度趋势数据
    参数:
        top_n - 要显示的热门车型数量
    """
    try:
        # 调用get_data函数获取数据
        data = get_data()

        # 将数据转换为DataFrame
        df = pd.DataFrame(data)


        df = df.rename(columns={
            'model': '车型',
            'year': '年份',
            'sales_volume': '销量'
        })

        # 按车型和年份分组计算总销量
        model_year_sales = df.groupby(['车型', '年份'])['销量'].sum().reset_index()

        # 找出销量最高的top_n个车型
        top_models = model_year_sales.groupby('车型')['销量'].sum().nlargest(top_n).index.tolist()

        # 准备趋势数据
        years = sorted(df['年份'].unique())
        trend_data = {}

        for model in top_models:
            model_data = model_year_sales[model_year_sales['车型'] == model]
            sales_by_year = {year: 0 for year in years}

            for _, row in model_data.iterrows():
                sales_by_year[row['年份']] = row['销量']

            trend_data[model] = [sales_by_year[year] for year in years]

        # 创建折线图
        line = (
            Line()
            .add_xaxis([str(year) for year in years])
            .set_global_opts(
                title_opts=opts.TitleOpts(title="热门车型年度销售趋势"),
                tooltip_opts=opts.TooltipOpts(trigger="axis"),
                legend_opts=opts.LegendOpts(pos_top="10%"),
                toolbox_opts=opts.ToolboxOpts(
                    feature=opts.ToolBoxFeatureOpts(
                        save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(),
                        data_view=opts.ToolBoxFeatureDataViewOpts(),
                        magic_type=opts.ToolBoxFeatureMagicTypeOpts(is_show=False),
                        restore=opts.ToolBoxFeatureRestoreOpts(),
                    )
                ),
                datazoom_opts=[
                    opts.DataZoomOpts(),
                    opts.DataZoomOpts(type_="inside")
                ],
                yaxis_opts=opts.AxisOpts(
                    name="销量",
                    axislabel_opts=opts.LabelOpts(formatter="{value} 台")
                )
            )
        )

        # 添加各车型数据
        for model, sales in trend_data.items():
            line.add_yaxis(
                series_name=model,
                y_axis=sales,
                is_smooth=True,
                symbol="circle",
                symbol_size=8,
                label_opts=opts.LabelOpts(is_show=False),
                linestyle_opts=opts.LineStyleOpts(width=3)
            )

        # 将图表转换为 JSON 数据
        chart_json = line.dump_options_with_quotes()

        return {
            'success': True,
            'chart_data': chart_json,
            'top_models': top_models,
            'years': years,
            'trend_data': trend_data
        }

    except Exception as e:
        return {
            'success': False,
            'error': f'获取车型趋势数据失败: {str(e)}'
        }